<template>
  <PageWrapper :title="orderInfoData?.projectName" contentBackground>
    <a-card title="项目信息" :bordered="false">
      <a-descriptions size="small" :column="3">
        <a-descriptions-item label="项目编号">{{ orderInfoData?.projectNumber }}</a-descriptions-item>
        <a-descriptions-item label="项目描述">{{ orderInfoData?.projectDescription }}</a-descriptions-item>
        <a-descriptions-item label="工程详细地址">{{ orderInfoData?.library?.address }}</a-descriptions-item>
        <a-descriptions-item label="项目状态">{{ orderInfoData?.projectStatus }}</a-descriptions-item>

        <a-descriptions-item label="发包单位"
          ><a>{{ orderInfoData?.contractingUnitVo?.name }}</a></a-descriptions-item
        >
        <a-descriptions-item label="所属库"
          ><a>{{ orderInfoData?.library?.name }}</a></a-descriptions-item
        >
        <a-descriptions-item label="总包主体"
          ><a>{{ orderInfoData?.companyInfo?.companyName }}</a></a-descriptions-item
        >

      </a-descriptions>
    </a-card>

    <a-card title="项目信息" :bordered="false">
      <a-row>
        <a-col :span="8"><a-statistic title="子合同总金额(元)" :precision="2" :value="orderInfoData?.subProjectAmount" /></a-col>
        <a-col :span="8"><a-statistic title="付款总金额(元)" :precision="2" :value="orderInfoData?.paymentTotal" /></a-col>
        <a-col :span="8"><a-statistic title="收票总金额(元)" :precision="2" :value="orderInfoData?.receiptsAndTaxTotal" /></a-col>

      </a-row>
    </a-card>




    <!--子项目-->
    <SubProjectModal :projectId="orderInfoData?.id"> </SubProjectModal>

    <!--任务-->
    <CTaskModal :projectId="orderInfoData?.id"> </CTaskModal>

    <a-tabs v-model:activeKey="activeTabKey" style="margin-left: 15px">
      <a-tab-pane key="quoteRecord" :force-render="true" tab="报价">
        <CProjectQuoteListInfoModal ref="projectQuoteRef"  :projectId="orderInfoData?.id"> </CProjectQuoteListInfoModal>
      </a-tab-pane>
      <a-tab-pane key="payment" :force-render="true" tab="付款记录">
        <PaymentRequestModal ref="paymentRef" :projectId="orderInfoData?.id"> </PaymentRequestModal>
      </a-tab-pane>
      <a-tab-pane key="invoice" :force-render="true" tab="收票记录">
        <PaymentInvoiceModal ref="invoiceRef" :projectId="orderInfoData?.id"> </PaymentInvoiceModal>
      </a-tab-pane>

      <a-tab-pane key="acceptance" :force-render="true" tab="验收记录">
        <AcceptanceRecordModal  ref="acceptanceRef":projectId="orderInfoData?.id"> </AcceptanceRecordModal>
      </a-tab-pane>

      <a-tab-pane key="contract" :force-render="true" tab="合同记录">
        <ContractInfoModal ref="contractRef" :projectId="orderInfoData?.id"> </ContractInfoModal>
      </a-tab-pane>

      <a-tab-pane key="fileRecord" :force-render="true" tab="相关文件">
        <fileRecordModal ref="fileRecordRef" :projectId="orderInfoData?.id"> </fileRecordModal>
      </a-tab-pane>
    </a-tabs>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, reactive } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Divider, Card, Empty, Descriptions, Steps, Tabs, Select, Statistic, Progress } from 'ant-design-vue';
  import { getOrderInfo } from './CProjectApplicationSimple.api';
  import { refundTimeTableSchema } from './data';
  import { QuestionCircleOutlined } from '@ant-design/icons-vue';
  import CTaskModal from '../task/CTaskListInfo.vue';
  import PaymentRequestModal from '../paymentrequest/CPaymentRequestListInfo.vue';
  import InvoiceApplyListInfoModal from '../invoiceapply/CInvoiceApplyListInfo.vue';
  import PaymentRecordListInfoModal from '../paymentrecord/CPaymentRecordListInfo.vue';
  import PaymentInvoiceModal from '../paymentInvoice/CPaymentInvoiceListInfo.vue';
  import ContractInfoModal from '../contrac/CContractListInfo.vue';
  import AcceptanceRecordModal from '../acceptancerecord/CAcceptanceRecordListInfo.vue';
  import fileRecordModal from '../filerecord/CFileRecordListInfo.vue';
  import ProjectHeadQuotesInfoModal from '../projectheadquote/CProjectHeadQuotesListInfo.vue';
  import projectheadquoteModal from '../projectheadquote/components/CProjectHeadQuotesModal.vue';
  import SubProjectModal from '../subproject/CSubProjectListInfo.vue';

  import { useRoute } from 'vue-router';
  import { ajaxGetDictItems } from '../common.api';
  import CContractModal from '@/views/contrac/components/CContractModal.vue';
  import CAcceptanceRecordModal from '@/views/acceptancerecord/components/CAcceptanceRecordModal.vue';
  import ViewFileDetail from '@/components/FileView/ViewFileDetail.vue';
  import CProjectStatusLogModal from '@/views/projectstatuslog/components/CProjectStatusLogModal.vue';
  import CProjectQuoteListInfoModal from '@/views/projectquote/CProjectQuoteListInfo.vue';
  import { useTabs } from "@/hooks/web/useTabs";
  const { createMessage } = useMessage();
  const registerModal = ref();
  const registerAcceptanceModal = ref();
  const registerContractModal = ref();

  const projectStatusLogRegisterModal = ref();

  // 从子组件获取 viewFileDetail 方法
  const viewFileDetail = ref();
  const viewFileDetailRef = ref();
  // 在 table 的插槽中使用 viewFileDetail 方法
  function handleViewFile(url) {
    viewFileDetail.value(url);
  }
  const projectQuoteRef   = ref()
  const paymentRef  = ref()
  const invoiceRef  = ref()
  const acceptanceRef  = ref()
  const contractRef  = ref()
  const fileRecordRef  = ref()

  const activeTabKey = ref('quoteRecord');
  export default defineComponent({
    components: {
      CProjectQuoteListInfoModal,
      QuestionCircleOutlined,
      CTaskModal,
      CProjectStatusLogModal,
      ViewFileDetail,
      CAcceptanceRecordModal,
      CContractModal,
      SubProjectModal,
      BasicTable,
      PaymentRequestModal,
      InvoiceApplyListInfoModal,
      PaymentRecordListInfoModal,
      PaymentInvoiceModal,
      ContractInfoModal,
      AcceptanceRecordModal,
      fileRecordModal,
      projectheadquoteModal,
      PageWrapper,
      ProjectHeadQuotesInfoModal,
      [Divider.name]: Divider,
      [Statistic.name]: Statistic,
      [Progress.name]: Progress,

      [Card.name]: Card,
      Empty,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      [Steps.name]: Steps,
      [Steps.Step.name]: Steps.Step,
      [Tabs.name]: Tabs,
      [Tabs.TabPane.name]: Tabs.TabPane,
    },
    setup() {
      const projectId = ref<string | null>(null);
      const contractIds = ref<string | null>(null);

      const projectStatusLogs = ref<any[]>([]);
      const currentStep = ref<number>(0);
      // 承包商下拉框选项
      let contractorOptions = ref();
      // 使用 useRoute 获取当前路由信息
      const route = useRoute();
      const orderInfoData = ref();
      const refundTimeTableData = ref([]);

      const [registerTimeTable] = useTable({
        // title: '子项目',
        columns: refundTimeTableSchema,
        pagination: true,
        dataSource: refundTimeTableData,
        showIndexColumn: false,
        scroll: { y: 300 },
      });

      // 定义所有可能的步骤
      const allSteps = reactive([
        { newStatus: '前期', remark: '', changeTime: '', num: 0 },
        { newStatus: '立项', remark: '', changeTime: '', num: 1 },
        { newStatus: '进行中', remark: '', changeTime: '', num: 2 },
        { newStatus: '验收阶段', remark: '', changeTime: '', num: 3 },
        { newStatus: '质保阶段', remark: '', changeTime: '', num: 4 },
        { newStatus: '完成', remark: '', changeTime: '', num: 5 },
        { newStatus: '废除', remark: '', changeTime: '', num: 6 },
      ]);
      // 自定义筛选逻辑
      const filterOption = (input: string, option: any) => {
        return option.label.toLowerCase().includes(input.toLowerCase());
      };

      /**
       * 上传合同
       */
      function uploadContract() {
        const record = { projectId: projectId.value, isProject: false };
        registerContractModal.value.disableSubmit = false;
        registerContractModal.value.add(record);
      }

      async function orderInfo() {
        try {
          const params = { id: projectId.value };
          const result = await getOrderInfo(params);

          orderInfoData.value = result;
          contractIds.value = result.contractId;

          // 动态设置流程进度数据
          projectStatusLogs.value = result.projectStatusLogList || [];
          //
          const data = projectStatusLogs.value[0];
          let statusFlag = true;
          // 根据返回的流程进度日志更新描述和时间
          let num = 0;
          allSteps.forEach((step, index) => {
            const log = projectStatusLogs.value.find((log) => log.newStatus === step.newStatus);
            if (log && statusFlag) {
              step.remark = log.remark || '';
              step.changeTime = log.changeTime || '';
              currentStep.value = step.num;
              if (data.newStatus === log.newStatus) {
                //后面的状态就不处理了
                statusFlag = false;
              }
            } else {
              step.remark = '';
              step.changeTime = '';
            }
          });

          //子项目
          const cSubProjectList = result.csubProjectList || [];

          for (var i = 0; i < cSubProjectList.length; i++) {
            const subProject = cSubProjectList[i];
            const refundTimeTable = {
              t1: subProject.subProjectName, //项目名称
              t2: subProject.contactId, //分包商
              t3: subProject.userId,
              t4: subProject.status,
            };
            refundTimeTableData.value.push(refundTimeTable);
          }
        } catch (error) {}
      }

      // 在页面加载时调用 getOrderInfo 方法
/*      const { setTitleByPath } = useTabs();
      onMounted(() => {
        projectId.value = route.query.projectId as string;
          orderInfo();
          debugger
           //设置tab名称
          const title = orderInfoData.value?.projectName? `主项目详情 - ${orderInfoData.value.projectName}`
            : '主项目详情';
            setTitleByPath(title,route.fullPath);
      });*/

      const { setTitleByPath } = useTabs();
      // 在页面加载时调用 getOrderInfo 方法
       onMounted(async () => {
          projectId.value = route.query.projectId as string;
         await orderInfo();
           //设置tab名称
          const title = orderInfoData.value?.projectName? `主项目 - ${orderInfoData.value.projectName}`
            : '主项目详情';
            setTitleByPath(title,route.fullPath);
      });



      async function dictCode(dictCode, dataId) {
        if (dataId) {
          const params = { dataId: dataId };
          const result = await ajaxGetDictItems(dictCode, params);
          if (result) {
            return result.text;
          }
          return dataId;
        }
      }

      /**
       * 刷新
       */
      function handleSuccess() {
        orderInfo();
        handleTabClick();
      }

      function quoteAdd() {
        const defaultValueRef = reactive<Record<string, any>>({
          projectId: projectId.value,
        });
        registerModal.value.disableSubmit = false;
        registerModal.value.add(defaultValueRef);
      }

  function handleTabClick() {
           projectQuoteRef.value?.refresh?.()
          paymentRef.value?.refresh?.()
          invoiceRef.value?.refresh?.()
           acceptanceRef.value?.refresh?.()
          contractRef.value?.refresh?.()
          fileRecordRef.value?.refresh?.()
  }

      return {
        quoteAdd,
        registerTimeTable,
        orderInfo,
        refundTimeTableData,
        route,
        orderInfoData,
        handleSuccess,
        projectStatusLogs,
        currentStep,
        allSteps,
        contractorOptions,
        filterOption,
        activeTabKey,
        dictCode,
        registerModal,
        uploadContract,
        registerContractModal,
        registerAcceptanceModal,
        handleViewFile,
        viewFileDetail,
        projectStatusLogRegisterModal,
        projectQuoteRef,
        paymentRef,
        invoiceRef,
        acceptanceRef,
        contractRef,
        fileRecordRef,
        handleTabClick,

      };
    },
  });
</script>
<style lang="less" scoped>
  .custom-label {
    font-weight: bold;
    color: gray;
    font-size: 18px;
  }
</style>
